<template>
  <div v-if="visible" class="custom-datetime-picker" :class="{ 'picker-closing': !showAnimation }">
    <div class="picker-overlay" @click="handleCancel"></div>
    <div class="picker-container" :class="{ 
      'picker-container--show': showAnimation,
      'picker-container--solar': dateType === 'solar',
      'picker-container--lunar': dateType === 'lunar', 
      'picker-container--sizhu': dateType === 'sizhu'
    }">
      <!-- 头部 -->
      <div class="picker-header">
        <div class="picker-header-top">
          <div class="picker-header-left">
            <div class="picker-tabs">
              <button class="picker-tab" :class="{ 'picker-tab--active': dateType === 'solar' }"
                @click="handleChangeDateType('solar')">
                公历
              </button>
              <button class="picker-tab" :class="{ 'picker-tab--active': dateType === 'lunar' }"
                @click="handleChangeDateType('lunar')">
                农历
              </button>
              <button class="picker-tab" :class="{ 'picker-tab--active': dateType === 'sizhu' }"
                @click="handleChangeDateType('sizhu')">
                四柱
              </button>
            </div>
            <button class="picker-today-btn" @click="handleToday" v-if="dateType === 'solar' || dateType === 'lunar'">今</button>
          </div>
          <button class="picker-btn picker-confirm" @click="handleConfirm">确定</button>
        </div>

        <!-- 快速输入区域 -->
        <div class="quick-input-container" v-if="dateType === 'solar'">
          <div class="input-group">
            <div class="input-wrapper">
              <input type="text" class="datetime-input" v-model="datetimeInput" placeholder="请输入出生年月日时分(格式199002030706)"
                maxlength="12" />
              <button class="clear-btn" v-if="datetimeInput.length > 0" type="button" @click="clearInput">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                    stroke-linejoin="round" />
                </svg>
              </button>
            </div>
            <button class="input-confirm-btn" :class="{ 'input-confirm-btn--active': datetimeInput.length > 0 }"
              :disabled="datetimeInput.length === 0" @click="handleInputConfirm">
              查询
            </button>
          </div>
        </div>
      </div>


      <!-- 选择器区域 -->
      <div class="picker-content" v-if="dateType !== 'sizhu'">
        <div class="picker-title">
          <span>年</span>
          <span>月</span>
          <span>日</span>
          <span>时</span>
          <span>分</span>
        </div>

        <div class="picker-wheels" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
          @touchend="handleTouchEnd">
          <!-- 年份选择 -->
          <div class="picker-wheel" ref="yearWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${yearOffset}px)` }">
              <div v-for="(year, index) in years" :key="year" class="wheel-item"
                :class="{ 'wheel-item--active': selectedYear === year }" @click="selectYear(year)">
                {{ year }}
              </div>
            </div>
            <!-- 选择框 -->
            <div class="picker-frame"></div>
          </div>

          <!-- 月份选择 -->
          <div class="picker-wheel" ref="monthWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${monthOffset}px)` }">
              <div v-for="(month, index) in months" :key="month" class="wheel-item"
                :class="{ 'wheel-item--active': selectedMonth === month }" @click="selectMonth(month)">
                {{ dateType === 'lunar' ? getLunarMonthLabel(selectedYear, month) : month }}
              </div>
            </div>
            <!-- 选择框 -->
            <div class="picker-frame"></div>
          </div>

          <!-- 日期选择 -->
          <div class="picker-wheel" ref="dayWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${dayOffset}px)` }">
              <div v-for="(day, index) in days" :key="day" class="wheel-item"
                :class="{ 'wheel-item--active': selectedDay === day }" @click="selectDay(day)">
                {{ dateType === 'lunar' ? dayArray[day - 1] : day }}
              </div>
            </div>
            <!-- 选择框 -->
            <div class="picker-frame"></div>
          </div>

          <!-- 小时选择 -->
          <div class="picker-wheel" ref="hourWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${hourOffset}px)` }">
              <div v-for="(hour, index) in hours" :key="hour" class="wheel-item"
                :class="{ 'wheel-item--active': selectedHour === hour }" @click="selectHour(hour)">
                {{ hour }}
              </div>
            </div>
            <!-- 选择框 -->
            <div class="picker-frame"></div>
          </div>

          <!-- 分钟选择 -->
          <div class="picker-wheel" ref="minuteWheel">
            <div class="wheel-content" :style="{ transform: `translateY(${minuteOffset}px)` }">
              <div v-for="(minute, index) in minutes" :key="minute" class="wheel-item"
                :class="{ 'wheel-item--active': selectedMinute === minute }" @click="selectMinute(minute)">
                {{ minute }}
              </div>
            </div>
            <!-- 选择框 -->
            <div class="picker-frame"></div>
          </div>
        </div>

        <!-- 整体遮罩层 -->
        <div class="picker-global-mask"></div>
      </div>

      <!-- 四柱内容区域 - 参考Dart实现 -->
      <div class="picker-sizhu-content" v-if="dateType === 'sizhu'">
        <!-- 四柱显示区域 -->
        <div class="sizhu-display">
          <!-- 标题行 -->
          <div class="sizhu-titles">
            <div class="sizhu-title">年柱</div>
            <div class="sizhu-title">月柱</div>
            <div class="sizhu-title">日柱</div>
            <div class="sizhu-title">时柱</div>
          </div>
          
          <!-- 天干行 -->
          <div class="sizhu-row">
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 0,
                   'sizhu-circle--disabled': !canClickPosition(0)
                 }"
                 @click="onSizhuCircleTap(0)"
                 :style="{ 
                   color: selectedNianGan ? getTianganColor(selectedNianGan) : '#64748b',
                   background: selectedNianGan ? getTianganLightColor(selectedNianGan) : '#f8f9fa'
                 }">
              {{ selectedNianGan || (currentStep === 0 ? '+' : '?') }}
            </div>
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 2,
                   'sizhu-circle--disabled': !canClickPosition(2)
                 }"
                 @click="onSizhuCircleTap(2)"
                 :style="{ 
                   color: selectedYueGan ? getTianganColor(selectedYueGan) : '#64748b',
                   background: selectedYueGan ? getTianganLightColor(selectedYueGan) : '#f8f9fa'
                 }">
              {{ selectedYueGan || (currentStep === 2 ? '+' : '?') }}
            </div>
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 3,
                   'sizhu-circle--disabled': !canClickPosition(4)
                 }"
                 @click="onSizhuCircleTap(4)"
                 :style="{ 
                   color: selectedRiGan ? getTianganColor(selectedRiGan) : '#64748b',
                   background: selectedRiGan ? getTianganLightColor(selectedRiGan) : '#f8f9fa'
                 }">
              {{ selectedRiGan || (currentStep === 3 ? '+' : '?') }}
            </div>
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 5 && !isAllSelected(),
                   'sizhu-circle--disabled': !canClickPosition(6)
                 }"
                 @click="onSizhuCircleTap(6)"
                 :style="{ 
                   color: selectedShiGan ? getTianganColor(selectedShiGan) : '#64748b',
                   background: selectedShiGan ? getTianganLightColor(selectedShiGan) : '#f8f9fa'
                 }">
              {{ selectedShiGan || (currentStep === 5 ? '+' : '?') }}
            </div>
          </div>
          
          <!-- 地支行 -->
          <div class="sizhu-row">
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 1,
                   'sizhu-circle--disabled': !canClickPosition(1)
                 }"
                 @click="onSizhuCircleTap(1)"
                 :style="{ 
                   color: selectedNianZhi ? getDizhiColor(selectedNianZhi) : '#64748b',
                   background: selectedNianZhi ? getDizhiLightColor(selectedNianZhi) : '#f8f9fa'
                 }">
              {{ selectedNianZhi || (currentStep === 1 ? '+' : '?') }}
            </div>
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 2,
                   'sizhu-circle--disabled': !canClickPosition(3)
                 }"
                 @click="onSizhuCircleTap(3)"
                 :style="{ 
                   color: selectedYueZhi ? getDizhiColor(selectedYueZhi) : '#64748b',
                   background: selectedYueZhi ? getDizhiLightColor(selectedYueZhi) : '#f8f9fa'
                 }">
              {{ selectedYueZhi || (currentStep === 2 ? '+' : '?') }}
            </div>
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 4,
                   'sizhu-circle--disabled': !canClickPosition(5)
                 }"
                 @click="onSizhuCircleTap(5)"
                 :style="{ 
                   color: selectedRiZhi ? getDizhiColor(selectedRiZhi) : '#64748b',
                   background: selectedRiZhi ? getDizhiLightColor(selectedRiZhi) : '#f8f9fa'
                 }">
              {{ selectedRiZhi || (currentStep === 4 ? '+' : '?') }}
            </div>
            <div class="sizhu-circle" 
                 :class="{ 
                   'sizhu-circle--active': currentStep === 5 && !isAllSelected(),
                   'sizhu-circle--disabled': !canClickPosition(7)
                 }"
                 @click="onSizhuCircleTap(7)"
                 :style="{ 
                   color: selectedShiZhi ? getDizhiColor(selectedShiZhi) : '#64748b',
                   background: selectedShiZhi ? getDizhiLightColor(selectedShiZhi) : '#f8f9fa'
                 }">
              {{ selectedShiZhi || (currentStep === 5 ? '+' : '?') }}
            </div>
          </div>
        </div>
        
        <!-- 选择区域 -->
        <div class="sizhu-selection">
          
          <!-- 天干选择 -->
          <div v-if="(currentStep === 0 || currentStep === 3) && !isAllSelected()" class="selection-grid">
            <div v-for="gan in tiangan" :key="gan" 
                 class="selection-item"
                 @click="currentStep === 0 ? selectNianGan(gan) : selectRiGan(gan)"
                 :style="{ color: getTianganColor(gan) }">
              {{ gan }}
            </div>
          </div>
          
          <!-- 地支选择 -->
          <div v-if="(currentStep === 1 || currentStep === 4) && !isAllSelected()" class="selection-grid">
            <div v-for="zhi in getValidZhiList(currentStep === 1 ? selectedNianGan! : selectedRiGan!)" :key="zhi" 
                 class="selection-item"
                 @click="currentStep === 1 ? selectNianZhi(zhi) : selectRiZhi(zhi)"
                 :style="{ color: getDizhiColor(zhi) }">
              {{ zhi }}
            </div>
          </div>
          
          <!-- 月柱选择 -->
          <div v-if="currentStep === 2 && selectedNianGan && !isAllSelected()" class="selection-grid selection-grid--grouped">
            <div v-for="(group, tiangan) in getYueZhuGrouped(selectedNianGan)" :key="tiangan" 
                 class="combination-group">
              <div class="group-dizhi-list">
                <div v-for="dizhi in group" :key="dizhi" 
                     class="dizhi-button"
                     :class="{ 'dizhi-button--large': group.length === 1, 'dizhi-button--small': group.length > 1 }"
                     @click="selectYueZhu(String(tiangan) + dizhi)">
                  <span class="button-tiangan" :style="{ color: getTianganColor(String(tiangan)) }">{{ tiangan }}</span>
                  <span class="button-dizhi" :style="{ color: getDizhiColor(dizhi) }">{{ dizhi }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 时柱选择 -->
          <div v-if="currentStep === 5 && selectedRiGan && !isAllSelected()" class="selection-grid selection-grid--grouped">
            <div v-for="(group, tiangan) in getShiZhuGrouped(selectedRiGan)" :key="tiangan" 
                 class="combination-group">
              <div class="group-dizhi-list">
                <div v-for="dizhi in group" :key="dizhi" 
                     class="dizhi-button"
                     :class="{ 'dizhi-button--large': group.length === 1, 'dizhi-button--small': group.length > 1 }"
                     @click="selectShiZhu(String(tiangan) + dizhi)">
                  <span class="button-tiangan" :style="{ color: getTianganColor(String(tiangan)) }">{{ tiangan }}</span>
                  <span class="button-dizhi" :style="{ color: getDizhiColor(dizhi) }">{{ dizhi }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 匹配日期选择 -->
          <div v-if="isAllSelected() && searchResults.length > 0" class="date-selection">
            <div class="date-selection-grid">
              <div
                v-for="(dateItem, index) in sortedSearchResults"
                :key="index"
                class="date-item"
                @click="selectDateResult(dateItem.gregorian)"
              >
                <div class="date-text">
                  <div class="date-gregorian">公历：{{ dateItem.gregorian }}</div>
                  <div class="date-lunar" v-if="dateItem.lunar">农历：{{ dateItem.lunar }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 无结果状态 -->
        <div v-if="isAllSelected() && searchResults.length === 0" class="no-results">
          <div class="no-results-icon">🔍</div>
          <div class="no-results-text">未找到匹配的日期</div>
          <div class="no-results-hint">请检查四柱是否正确</div>
        </div>
        
        <!-- 底部按钮区域 -->
        <div class="sizhu-buttons">
          <button v-if="currentStep > 0" class="btn-previous" @click="goToPreviousStep">
            上一步
          </button>
          <button v-if="hasAnySelection()" class="btn-clear" @click="clearAllSelections">
            清空
          </button>
        </div>
      </div>


    </div>
  </div>

  <!-- 自定义 Toast -->
  <div v-if="toastVisible" class="custom-toast" :class="`toast-${toastType}`" @click="hideToast">
    <div class="toast-content">
      <div class="toast-icon">
        <svg v-if="toastType === 'error'" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <svg v-else-if="toastType === 'success'" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <svg v-else-if="toastType === 'warning'" width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
        <svg v-else width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M13 16H12V12H11M12 8H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </div>
      <div class="toast-message">{{ toastMessage }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { 
  SolarTime, 
  LunarHour, 
  EightChar, 
  SixtyCycle, 
  HeavenStem, 
  EarthBranch,
  Gender,
  YinYang,
  LunarYear,
  LunarMonth,
  LunarDay
} from './bazi-calculation-core'

// Props
interface Props {
  modelValue: boolean
  defaultDateTime?: string
  dateType?: 'solar' | 'lunar' | 'sizhu'
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  defaultDateTime: '',
  dateType: 'solar'
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [result: {
    solar: string;
    lunar: string;
    eightChar: string;
    dateType: 'solar' | 'lunar' | 'sizhu';
  }]
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 日期类型：solar公历，lunar农历，sizhu四柱
const dateType = ref<'solar' | 'lunar' | 'sizhu'>(props.dateType || 'solar')

// 监听 dateType prop 变化
watch(() => props.dateType, (newType) => {
  if (newType) {
    dateType.value = newType
  }
})

// 动画状态
const showAnimation = ref(false)

// 快速输入相关
const datetimeInput = ref('')

// 自定义 Toast 系统
const toastVisible = ref(false)
const toastMessage = ref('')
const toastType = ref<'success' | 'error' | 'warning' | 'info'>('error')
const toastTimer = ref<number | null>(null)

// 显示 Toast
const showCustomToast = (message: string, type: 'success' | 'error' | 'warning' | 'info' = 'error', duration: number = 3000) => {
  // 清除之前的定时器
  if (toastTimer.value) {
    clearTimeout(toastTimer.value)
  }
  
  toastMessage.value = message
  toastType.value = type
  toastVisible.value = true
  
  // 自动隐藏
  toastTimer.value = setTimeout(() => {
    hideToast()
  }, duration)
}

// 隐藏 Toast
const hideToast = () => {
  toastVisible.value = false
  if (toastTimer.value) {
    clearTimeout(toastTimer.value)
    toastTimer.value = null
  }
}

// 优化 Toast 显示方法（保持兼容性）
const showOptimizedToast = (message: string) => {
  showCustomToast(message, 'error', 3000)
}

// 初始化农历当前时间
const initializeLunarCurrentTime = () => {
  try {
    // 使用默认的1990年时间，而不是当前时间
    const defaultTime = new Date(1990, new Date().getMonth(), new Date().getDate(), new Date().getHours(), new Date().getMinutes())
    const solarTime = SolarTime.fromYmdHms(
      defaultTime.getFullYear(), 
      defaultTime.getMonth() + 1, 
      defaultTime.getDate(), 
      defaultTime.getHours(), 
      defaultTime.getMinutes(), 
      0
    )
    
    const solarDay = solarTime.getSolarDay()
    const lunarDayObj = solarDay.getLunarDay()
    const lunarMonthObj = lunarDayObj.getLunarMonth()
    const lunarYearObj = lunarMonthObj.getLunarYear()
    
    // 设置农历年月日
    lunarYear.value = lunarYearObj.getYear()
    
    // 获取农历月份（考虑闰月）
    const lunarMonths = getLunarMonths(lunarYearObj.getYear())
    const currentLunarMonth = lunarMonthObj.getMonth()
    const isLeap = lunarMonthObj.isLeap()
    
    // 找到对应的月份值
    const monthValue = isLeap ? currentLunarMonth + 12 : currentLunarMonth
    const validMonth = lunarMonths.find(m => m.value === monthValue)
    
    if (validMonth) {
      lunarMonth.value = monthValue
    } else {
      // 如果找不到对应的月份，使用第一个可用月份
      lunarMonth.value = lunarMonths[0]?.value || 1
    }
    
    lunarDay.value = lunarDayObj.getDay()
    lunarHour.value = defaultTime.getHours()
    lunarMinute.value = defaultTime.getMinutes()
  } catch (error) {
    console.error('农历初始化失败：', error)
    // 如果转换失败，使用公历日期
    const today = new Date()
    lunarYear.value = today.getFullYear()
    lunarMonth.value = today.getMonth() + 1
    lunarDay.value = today.getDate()
    lunarHour.value = today.getHours()
    lunarMinute.value = today.getMinutes()
  }
}



// 公历选中的值
const solarYear = ref(new Date().getFullYear())
const solarMonth = ref(new Date().getMonth() + 1)
const solarDay = ref(new Date().getDate())
const solarHour = ref(new Date().getHours())
const solarMinute = ref(new Date().getMinutes())

// 农历选中的值
const lunarYear = ref(new Date().getFullYear())
const lunarMonth = ref(new Date().getMonth() + 1)
const lunarDay = ref(new Date().getDate())
const lunarHour = ref(new Date().getHours())
const lunarMinute = ref(new Date().getMinutes())

// 当前选中的值（根据模式切换）
const selectedYear = computed({
  get: () => dateType.value === 'solar' ? solarYear.value : lunarYear.value,
  set: (value) => {
    if (dateType.value === 'solar') {
      solarYear.value = value
    } else {
      lunarYear.value = value
    }
  }
})

const selectedMonth = computed({
  get: () => dateType.value === 'solar' ? solarMonth.value : lunarMonth.value,
  set: (value) => {
    if (dateType.value === 'solar') {
      solarMonth.value = value
    } else {
      lunarMonth.value = value
    }
  }
})

const selectedDay = computed({
  get: () => dateType.value === 'solar' ? solarDay.value : lunarDay.value,
  set: (value) => {
    if (dateType.value === 'solar') {
      solarDay.value = value
    } else {
      lunarDay.value = value
    }
  }
})

const selectedHour = computed({
  get: () => dateType.value === 'solar' ? solarHour.value : lunarHour.value,
  set: (value) => {
    if (dateType.value === 'solar') {
      solarHour.value = value
    } else {
      lunarHour.value = value
    }
  }
})

const selectedMinute = computed({
  get: () => dateType.value === 'solar' ? solarMinute.value : lunarMinute.value,
  set: (value) => {
    if (dateType.value === 'solar') {
      solarMinute.value = value
    } else {
      lunarMinute.value = value
    }
  }
})

// 年份范围 - 根据农历数据范围设置为1801-2100
const minYear = 1801
const maxYear = 2100


// 轮盘引用
const yearWheel = ref<HTMLElement>()
const monthWheel = ref<HTMLElement>()
const dayWheel = ref<HTMLElement>()
const hourWheel = ref<HTMLElement>()
const minuteWheel = ref<HTMLElement>()

// 轮盘偏移量
const yearOffset = ref(0)
const monthOffset = ref(0)
const dayOffset = ref(0)
const hourOffset = ref(0)
const minuteOffset = ref(0)

// 轮盘高度
const ITEM_HEIGHT = 40

// 触摸相关 - 简化版本
const touchStartY = ref(0)
const touchStartTime = ref(0)
const isDragging = ref(false)

// 生成选项数据
const years = computed(() => {
  const years = []
  for (let i = minYear; i <= maxYear; i++) {
    years.push(i)
  }
  return years
})

const months = computed(() => {
  if (dateType.value === 'solar') {
    return Array.from({ length: 12 }, (_, i) => i + 1)
  } else {
    // 农历月份处理 - 包含闰月
    const lunarMonths = getLunarMonths(selectedYear.value)
    return lunarMonths.map(m => m.value)
  }
})

const days = computed(() => {
  if (dateType.value === 'solar') {
    const daysInMonth = new Date(selectedYear.value, selectedMonth.value, 0).getDate()
    return Array.from({ length: daysInMonth }, (_, i) => i + 1)
  } else {
    // 农历日期处理 - 返回数字，显示时使用农历名称
    const daysInMonth = getLunarMonthDays(selectedYear.value, selectedMonth.value)
    return Array.from({ length: daysInMonth }, (_, i) => i + 1)
  }
})

const hours = computed(() => {
  return Array.from({ length: 24 }, (_, i) => i)
})

const minutes = computed(() => {
  return Array.from({ length: 60 }, (_, i) => i)
})


// 天干地支数据
const tiangan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸']
const dizhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']

// 使用 bazi-utils 中的农历工具类

// 农历月份和日期显示数组
const monthArray = ['正月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '冬月', '腊月']
const dayArray = ["初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "廿十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "卅十"]


// 获取农历月份天数（使用工具类）
const getLunarMonthDays = (year: number, month: number): number => {
  try {
    // 判断是正常月份还是闰月
    const isLeapMonth = month > 12
    const actualMonth = isLeapMonth ? month - 12 : month
    
    // 使用工具类获取农历月份
    const lunarMonth = LunarMonth.fromYm(year, isLeapMonth ? -actualMonth : actualMonth)
    return lunarMonth.getDayCount()
  } catch (error) {
    // 如果出错，返回默认值
    return 30
  }
}

// 获取农历年份的所有月份列表（使用工具类）
const getLunarMonths = (year: number): Array<{ value: number; label: string; isLeap: boolean }> => {
  const months: Array<{ value: number; label: string; isLeap: boolean }> = []
  
  try {
    const lunarYear = LunarYear.fromYear(year)
    const leapMonth = lunarYear.getLeapMonth()
    
    for (let i = 1; i <= 12; i++) {
      // 添加正常月份
      months.push({
        value: i,
        label: monthArray[i - 1] || `${i}月`,
        isLeap: false
      })
      
      // 如果当前月份是闰月，在该月后插入闰月
      if (leapMonth === i) {
        months.push({
          value: i + 12, // 使用13+表示闰月
          label: `闰${monthArray[i - 1] || `${i}月`}`,
          isLeap: true
        })
      }
    }
  } catch (error) {
    // 如果出错，返回默认的12个月
    for (let i = 1; i <= 12; i++) {
      months.push({
        value: i,
        label: monthArray[i - 1] || `${i}月`,
        isLeap: false
      })
    }
  }
  
  return months
}

// 获取农历月份标签
const getLunarMonthLabel = (year: number, month: number): string => {
  const lunarMonths = getLunarMonths(year)
  const found = lunarMonths.find(m => m.value === month)
  if (found) {
    return found.label
  }
  // 如果找不到，尝试使用月份数组（正常月份）
  if (month >= 1 && month <= 12) {
    return monthArray[month - 1] || month.toString()
  }
  return month.toString()
}

// 五行颜色映射
const wuxingColors = {
  // 天干五行颜色
  tiangan: {
    '甲': '#22c55e', // 木 - 绿色
    '乙': '#22c55e', // 木 - 绿色
    '丙': '#ef4444', // 火 - 红色
    '丁': '#ef4444', // 火 - 红色
    '戊': '#92400e', // 土 - 大地色（棕色）
    '己': '#92400e', // 土 - 大地色（棕色）
    '庚': '#d97706', // 金 - 金色
    '辛': '#d97706', // 金 - 金色
    '壬': '#3b82f6', // 水 - 蓝色
    '癸': '#3b82f6'  // 水 - 蓝色
  },
  // 地支五行颜色
  dizhi: {
    '子': '#3b82f6', // 水 - 蓝色
    '丑': '#92400e', // 土 - 大地色（棕色）
    '寅': '#22c55e', // 木 - 绿色
    '卯': '#22c55e', // 木 - 绿色
    '辰': '#92400e', // 土 - 大地色（棕色）
    '巳': '#ef4444', // 火 - 红色
    '午': '#ef4444', // 火 - 红色
    '未': '#92400e', // 土 - 大地色（棕色）
    '申': '#d97706', // 金 - 金色
    '酉': '#d97706', // 金 - 金色
    '戌': '#92400e', // 土 - 大地色（棕色）
    '亥': '#3b82f6'  // 水 - 蓝色
  }
}

// 获取天干五行颜色
const getTianganColor = (tg: string) => {
  return wuxingColors.tiangan[tg as keyof typeof wuxingColors.tiangan] || '#64748b'
}

// 获取地支五行颜色
const getDizhiColor = (dz: string) => {
  return wuxingColors.dizhi[dz as keyof typeof wuxingColors.dizhi] || '#64748b'
}

// 获取天干浅色背景
const getTianganLightColor = (tg: string) => {
  const colorMap: { [key: string]: string } = {
    '甲': '#dcfce7', // 木 - 浅绿色
    '乙': '#dcfce7', // 木 - 浅绿色
    '丙': '#fef2f2', // 火 - 浅红色
    '丁': '#fef2f2', // 火 - 浅红色
    '戊': '#fef7ed', // 土 - 浅棕色
    '己': '#fef7ed', // 土 - 浅棕色
    '庚': '#fef3c7', // 金 - 浅金色
    '辛': '#fef3c7', // 金 - 浅金色
    '壬': '#eff6ff', // 水 - 浅蓝色
    '癸': '#eff6ff'  // 水 - 浅蓝色
  }
  return colorMap[tg] || '#f4f4f4'
}

// 获取地支浅色背景
const getDizhiLightColor = (dz: string) => {
  const colorMap: { [key: string]: string } = {
    '子': '#eff6ff', // 水 - 浅蓝色
    '丑': '#fef7ed', // 土 - 浅棕色
    '寅': '#dcfce7', // 木 - 浅绿色
    '卯': '#dcfce7', // 木 - 浅绿色
    '辰': '#fef7ed', // 土 - 浅棕色
    '巳': '#fef2f2', // 火 - 浅红色
    '午': '#fef2f2', // 火 - 浅红色
    '未': '#fef7ed', // 土 - 浅棕色
    '申': '#fef3c7', // 金 - 浅金色
    '酉': '#fef3c7', // 金 - 浅金色
    '戌': '#fef7ed', // 土 - 浅棕色
    '亥': '#eff6ff'  // 水 - 浅蓝色
  }
  return colorMap[dz] || '#f4f4f4'
}

// 四柱选择状态 - 参考Dart实现
const selectedNianGan = ref<string | null>(null)
const selectedNianZhi = ref<string | null>(null)
const selectedYueGan = ref<string | null>(null)
const selectedYueZhi = ref<string | null>(null)
const selectedRiGan = ref<string | null>(null)
const selectedRiZhi = ref<string | null>(null)
const selectedShiGan = ref<string | null>(null)
const selectedShiZhi = ref<string | null>(null)

// 当前步骤 - 参考Dart的currentStep
const currentStep = ref(0)

// 五虎遁规律 - 月柱组合数据（基于年干）
const yueZhuCombinations = {
  // 甲己之年：丙作首（正月丙寅）
  '甲': ['丙寅', '丁卯', '戊辰', '己巳', '庚午', '辛未', '壬申', '癸酉', '甲戌', '乙亥', '丙子', '丁丑'],
  '己': ['丙寅', '丁卯', '戊辰', '己巳', '庚午', '辛未', '壬申', '癸酉', '甲戌', '乙亥', '丙子', '丁丑'],
  
  // 乙庚之年：戊为头（正月戊寅）
  '乙': ['戊寅', '己卯', '庚辰', '辛巳', '壬午', '癸未', '甲申', '乙酉', '丙戌', '丁亥', '戊子', '己丑'],
  '庚': ['戊寅', '己卯', '庚辰', '辛巳', '壬午', '癸未', '甲申', '乙酉', '丙戌', '丁亥', '戊子', '己丑'],
  
  // 丙辛之年：庚寅上（正月庚寅）
  '丙': ['庚寅', '辛卯', '壬辰', '癸巳', '甲午', '乙未', '丙申', '丁酉', '戊戌', '己亥', '庚子', '辛丑'],
  '辛': ['庚寅', '辛卯', '壬辰', '癸巳', '甲午', '乙未', '丙申', '丁酉', '戊戌', '己亥', '庚子', '辛丑'],
  
  // 丁壬之年：壬寅顺水流（正月壬寅）
  '丁': ['壬寅', '癸卯', '甲辰', '乙巳', '丙午', '丁未', '戊申', '己酉', '庚戌', '辛亥', '壬子', '癸丑'],
  '壬': ['壬寅', '癸卯', '甲辰', '乙巳', '丙午', '丁未', '戊申', '己酉', '庚戌', '辛亥', '壬子', '癸丑'],
  
  // 戊癸之年：甲寅何处起（正月甲寅）
  '戊': ['甲寅', '乙卯', '丙辰', '丁巳', '戊午', '己未', '庚申', '辛酉', '壬戌', '癸亥', '甲子', '乙丑'],
  '癸': ['甲寅', '乙卯', '丙辰', '丁巳', '戊午', '己未', '庚申', '辛酉', '壬戌', '癸亥', '甲子', '乙丑']
}

// 五鼠遁规律 - 时柱组合数据（基于日干）
const shiZhuCombinations = {
  // 甲己日：甲子时开始
  '甲': ['甲子', '乙丑', '丙寅', '丁卯', '戊辰', '己巳', '庚午', '辛未', '壬申', '癸酉', '甲戌', '乙亥'],
  '己': ['甲子', '乙丑', '丙寅', '丁卯', '戊辰', '己巳', '庚午', '辛未', '壬申', '癸酉', '甲戌', '乙亥'],
  
  // 乙庚日：丙子时开始
  '乙': ['丙子', '丁丑', '戊寅', '己卯', '庚辰', '辛巳', '壬午', '癸未', '甲申', '乙酉', '丙戌', '丁亥'],
  '庚': ['丙子', '丁丑', '戊寅', '己卯', '庚辰', '辛巳', '壬午', '癸未', '甲申', '乙酉', '丙戌', '丁亥'],
  
  // 丙辛日：戊子时开始
  '丙': ['戊子', '己丑', '庚寅', '辛卯', '壬辰', '癸巳', '甲午', '乙未', '丙申', '丁酉', '戊戌', '己亥'],
  '辛': ['戊子', '己丑', '庚寅', '辛卯', '壬辰', '癸巳', '甲午', '乙未', '丙申', '丁酉', '戊戌', '己亥'],
  
  // 丁壬日：庚子时开始
  '丁': ['庚子', '辛丑', '壬寅', '癸卯', '甲辰', '乙巳', '丙午', '丁未', '戊申', '己酉', '庚戌', '辛亥'],
  '壬': ['庚子', '辛丑', '壬寅', '癸卯', '甲辰', '乙巳', '丙午', '丁未', '戊申', '己酉', '庚戌', '辛亥'],
  
  // 戊癸日：壬子时开始
  '戊': ['壬子', '癸丑', '甲寅', '乙卯', '丙辰', '丁巳', '戊午', '己未', '庚申', '辛酉', '壬戌', '癸亥'],
  '癸': ['壬子', '癸丑', '甲寅', '乙卯', '丙辰', '丁巳', '戊午', '己未', '庚申', '辛酉', '壬戌', '癸亥']
}

// 判断天干是否为阳干 - 参考Dart实现
const isYangGan = (gan: string) => {
  // 阳干：甲、丙、戊、庚、壬
  return ['甲', '丙', '戊', '庚', '壬'].includes(gan)
}

// 根据天干获取对应的地支列表（阴阳配对）- 参考Dart实现
const getValidZhiList = (gan: string) => {
  if (isYangGan(gan)) {
    // 阳干配阳支
    return ['子', '寅', '辰', '午', '申', '戌']
  } else {
    // 阴干配阴支
    return ['丑', '卯', '巳', '未', '酉', '亥']
  }
}

// 根据年干获取月柱组合列表 - 参考Dart实现
const getYueZhuList = (nianGan: string) => {
  return yueZhuCombinations[nianGan as keyof typeof yueZhuCombinations] || []
}

// 根据日干获取时柱组合列表 - 参考Dart实现
const getShiZhuList = (riGan: string) => {
  return shiZhuCombinations[riGan as keyof typeof shiZhuCombinations] || []
}

// 根据年干获取月柱分组列表
const getYueZhuGrouped = (nianGan: string) => {
  const combinations = getYueZhuList(nianGan)
  const grouped: { [key: string]: string[] } = {}
  
  combinations.forEach(combination => {
    const tiangan = combination[0] || ''
    const dizhi = combination[1] || ''
    if (!grouped[tiangan]) {
      grouped[tiangan] = []
    }
    grouped[tiangan].push(dizhi)
  })
  
  return grouped
}

// 根据日干获取时柱分组列表
const getShiZhuGrouped = (riGan: string) => {
  const combinations = getShiZhuList(riGan)
  const grouped: { [key: string]: string[] } = {}
  
  combinations.forEach(combination => {
    const tiangan = combination[0] || ''
    const dizhi = combination[1] || ''
    if (!grouped[tiangan]) {
      grouped[tiangan] = []
    }
    grouped[tiangan].push(dizhi)
  })
  
  return grouped
}

// 检查是否有任何选择 - 参考Dart实现
const hasAnySelection = () => {
  return selectedNianGan.value !== null ||
    selectedNianZhi.value !== null ||
    selectedYueGan.value !== null ||
    selectedYueZhi.value !== null ||
    selectedRiGan.value !== null ||
    selectedRiZhi.value !== null ||
    selectedShiGan.value !== null ||
    selectedShiZhi.value !== null
}

// 检查是否所有四柱都已选择 - 参考Dart实现
const isAllSelected = () => {
  return selectedNianGan.value !== null &&
    selectedNianZhi.value !== null &&
    selectedYueGan.value !== null &&
    selectedYueZhi.value !== null &&
    selectedRiGan.value !== null &&
    selectedRiZhi.value !== null &&
    selectedShiGan.value !== null &&
    selectedShiZhi.value !== null
}

// 选择年柱天干 - 参考Dart实现
const selectNianGan = (gan: string) => {
  selectedNianGan.value = gan
  currentStep.value = 1
  // 清空之前可能不匹配的年支
  if (selectedNianZhi.value !== null) {
    const validZhiList = getValidZhiList(gan)
    if (!validZhiList.includes(selectedNianZhi.value)) {
      selectedNianZhi.value = null
    }
  }
}

// 选择年柱地支 - 参考Dart实现
const selectNianZhi = (zhi: string) => {
  selectedNianZhi.value = zhi
  currentStep.value = 2
}

// 选择月柱组合 - 参考Dart实现
const selectYueZhu = (combination: string) => {
  selectedYueGan.value = combination[0] || null
  selectedYueZhi.value = combination[1] || null
  currentStep.value = 3
}

// 选择日柱天干 - 参考Dart实现
const selectRiGan = (gan: string) => {
  selectedRiGan.value = gan
  currentStep.value = 4
  // 清空之前可能不匹配的日支
  if (selectedRiZhi.value !== null) {
    const validZhiList = getValidZhiList(gan)
    if (!validZhiList.includes(selectedRiZhi.value)) {
      selectedRiZhi.value = null
    }
  }
}

// 选择日柱地支 - 参考Dart实现
const selectRiZhi = (zhi: string) => {
  selectedRiZhi.value = zhi
  currentStep.value = 5
}

// 选择时柱组合 - 参考Dart实现
const selectShiZhu = (combination: string) => {
  selectedShiGan.value = combination[0] || null
  selectedShiZhi.value = combination[1] || null
  // 时柱选择完成，可以开始反查
  if (isAllSelected()) {
    // 开始反查日期
    startDateSearch()
  }
}

// 反查日期结果
const searchResults = ref<Array<{gregorian: string, lunar: string}>>([])

// 排序后的搜索结果（从新到旧）
const sortedSearchResults = computed(() => {
  return [...searchResults.value].sort((a, b) => {
    // 从格式化日期字符串中解析日期进行比较
    const dateA = parseGregorianToDateTime(a.gregorian)
    const dateB = parseGregorianToDateTime(b.gregorian)
    return new Date(dateB).getTime() - new Date(dateA).getTime()
  })
})

// 开始反查日期 - 使用工具类内置方法（参考后台实现）
const startDateSearch = () => {
  if (!isAllSelected()) return
  
  try {
    // 构建四柱对象
    const yearCycle = SixtyCycle.fromName(`${selectedNianGan.value}${selectedNianZhi.value}`)
    const monthCycle = SixtyCycle.fromName(`${selectedYueGan.value}${selectedYueZhi.value}`)
    const dayCycle = SixtyCycle.fromName(`${selectedRiGan.value}${selectedRiZhi.value}`)
    const hourCycle = SixtyCycle.fromName(`${selectedShiGan.value}${selectedShiZhi.value}`)
    
    const targetEightChar = new EightChar(yearCycle, monthCycle, dayCycle, hourCycle)
    
    // 使用工具类内置方法获取匹配的日期（参考后台实现）
    const solarTimes = targetEightChar.getSolarTimes(1801, 2100)
    
    // 格式化结果（参考后台格式）
    searchResults.value = solarTimes.slice(0, 50).map(solarTime => {
      const solarDay = solarTime.getSolarDay()
      const lunarDay = solarDay.getLunarDay()
      const lunarMonth = lunarDay.getLunarMonth()
      const lunarYear = lunarMonth.getLunarYear()
      const lunarHour = solarTime.getLunarHour(true)
      const hourName = lunarHour.getSixtyCycle().getEarthBranch().getName() + '时'
      
      // 公历格式
      const gregorian = `${solarTime.getYear()}年${solarTime.getMonth().toString().padStart(2, '0')}月${solarTime.getDay().toString().padStart(2, '0')}日 ${solarTime.getHour().toString().padStart(2, '0')}:${solarTime.getMinute().toString().padStart(2, '0')}`
      
      // 农历格式
      const lunarMonthName = lunarMonth.getName()
      const lunarDayName = lunarDay.getName()
      const lunarYearNumber = lunarYear.getYear()
      // 移除农历月份和日期名称中可能包含的年份信息
      const cleanMonthName = lunarMonthName.replace(/\d+年/g, '')
      const cleanDayName = lunarDayName.replace(/\d+年/g, '')
      const lunar = `${lunarYearNumber}年${cleanMonthName}${cleanDayName}日 ${hourName}`
      
      return { gregorian, lunar }
    })
  } catch (error) {
    console.error('反查出现错误：', error)
    searchResults.value = []
  }
}

// 删除复杂的搜索函数和格式化函数，直接使用工具类内置方法










// 将格式化日期字符串转换为标准日期时间格式
// 输入: "2094年12月11日 18:00"
// 输出: "2094-12-11 18:00:00"
const parseGregorianToDateTime = (gregorian: string): string => {
  const match = gregorian.match(/(\d{4})年(\d{1,2})月(\d{1,2})日 (\d{1,2}):(\d{1,2})/)
  if (!match || match.length < 6) {
    // 如果解析失败，尝试返回当前时间
    const now = new Date()
    return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
  }
  const [, year, month, day, hour, minute] = match
  return `${year}-${month!.padStart(2, '0')}-${day!.padStart(2, '0')} ${hour!.padStart(2, '0')}:${minute!.padStart(2, '0')}:00`
}

// 选择日期结果
const selectDateResult = (gregorian: string) => {
  // 构建四柱字符串并发送给父组件
  const sizhuStr = `${selectedNianGan.value}${selectedNianZhi.value} ${selectedYueGan.value}${selectedYueZhi.value} ${selectedRiGan.value}${selectedRiZhi.value} ${selectedShiGan.value}${selectedShiZhi.value}`
  
  // 将格式化日期转换为标准日期时间格式
  const dateTime = parseGregorianToDateTime(gregorian)
  
  // 计算对应的农历日期
  let lunarDate = ''
  try {
    // 从格式化日期字符串中解析日期
    const match = gregorian.match(/(\d{4})年(\d{1,2})月(\d{1,2})日 (\d{1,2}):(\d{1,2})/)
    if (match && match.length >= 6) {
      const [, year, month, day, hour, minute] = match
      if (year && month && day && hour && minute) {
        const solarTime = SolarTime.fromYmdHms(
          parseInt(year), 
          parseInt(month), 
          parseInt(day), 
          parseInt(hour), 
          parseInt(minute), 
          0
        )
        
        // 获取农历信息
        const solarDayObj = solarTime.getSolarDay()
        const lunarDay = solarDayObj.getLunarDay()
        const lunarMonth = lunarDay.getLunarMonth()
        const lunarYear = lunarMonth.getLunarYear()
        const lunarHourForTime = solarTime.getLunarHour(true)
        const hourName = lunarHourForTime.getSixtyCycle().getEarthBranch().getName() + '时'
        
        const lunarMonthName = lunarMonth.getName()
        const lunarDayName = lunarDay.getName()
        const lunarYearNumber = lunarYear.getYear()
        // 移除农历月份和日期名称中可能包含的年份信息
        const cleanMonthName = lunarMonthName.replace(/\d+年/g, '')
        const cleanDayName = lunarDayName.replace(/\d+年/g, '')
        lunarDate = `${lunarYearNumber}年${cleanMonthName}${cleanDayName}日 ${hourName}`
      }
    }
  } catch (error) {
    console.error('农历转换失败：', error)
  }
  
  // 发送结果给父组件
  emit('confirm', {
    solar: dateTime,
    lunar: lunarDate,
    eightChar: sizhuStr,
    dateType: 'sizhu'
  })
  
  // 清除数据并关闭弹窗
  clearAllSelections()
  showAnimation.value = false
  setTimeout(() => {
    visible.value = false
  }, 300)
}

// 上一步操作 - 参考Dart实现
const goToPreviousStep = () => {
  switch (currentStep.value) {
    case 1:
      currentStep.value = 0
      selectedNianGan.value = null
      break
    case 2:
      currentStep.value = 1
      selectedNianZhi.value = null
      break
    case 3:
      currentStep.value = 2
      selectedYueGan.value = null
      selectedYueZhi.value = null
      break
    case 4:
      currentStep.value = 3
      selectedRiGan.value = null
      break
    case 5:
      currentStep.value = 4
      selectedRiZhi.value = null
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
    case 6:
      // 如果时柱已选择完成，清空时柱
      if (selectedShiGan.value !== null && selectedShiZhi.value !== null) {
        selectedShiGan.value = null
        selectedShiZhi.value = null
      } else {
        // 回到选择日柱地支
        currentStep.value = 5
        selectedRiZhi.value = null
      }
      break
  }
}

// 清空所有选择 - 参考Dart实现
const clearAllSelections = () => {
  selectedNianGan.value = null
  selectedNianZhi.value = null
  selectedYueGan.value = null
  selectedYueZhi.value = null
  selectedRiGan.value = null
  selectedRiZhi.value = null
  selectedShiGan.value = null
  selectedShiZhi.value = null
  currentStep.value = 0
}

// 检查是否可以点击某个位置 - 严格按照顺序
const canClickPosition = (position: number) => {
  switch (position) {
    case 0: // 年干 - 总是可以点击
      return true
    case 1: // 年支 - 需要年干已选择
      return selectedNianGan.value !== null
    case 2: // 月干 - 需要年柱完成
    case 3: // 月支 - 需要年柱完成
      return selectedNianGan.value !== null && selectedNianZhi.value !== null
    case 4: // 日干 - 需要月柱完成
      return selectedNianGan.value !== null && selectedNianZhi.value !== null && 
             selectedYueGan.value !== null && selectedYueZhi.value !== null
    case 5: // 日支 - 需要日干已选择
      return selectedNianGan.value !== null && selectedNianZhi.value !== null && 
             selectedYueGan.value !== null && selectedYueZhi.value !== null &&
             selectedRiGan.value !== null
    case 6: // 时干 - 需要日柱完成
    case 7: // 时支 - 需要日柱完成
      return selectedNianGan.value !== null && selectedNianZhi.value !== null && 
             selectedYueGan.value !== null && selectedYueZhi.value !== null &&
             selectedRiGan.value !== null && selectedRiZhi.value !== null
    default:
      return false
  }
}

// 处理四柱圆圈点击 - 参考Dart实现
const onSizhuCircleTap = (position: number) => {
  // 检查是否可以点击
  if (!canClickPosition(position)) {
    return
  }
  
  switch (position) {
    case 0: // 年干
      currentStep.value = 0
      selectedNianGan.value = null
      selectedNianZhi.value = null
      selectedYueGan.value = null
      selectedYueZhi.value = null
      selectedRiGan.value = null
      selectedRiZhi.value = null
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
    case 1: // 年支
      currentStep.value = 1
      selectedNianZhi.value = null
      selectedYueGan.value = null
      selectedYueZhi.value = null
      selectedRiGan.value = null
      selectedRiZhi.value = null
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
    case 2: // 月干
    case 3: // 月支
      currentStep.value = 2
      selectedYueGan.value = null
      selectedYueZhi.value = null
      selectedRiGan.value = null
      selectedRiZhi.value = null
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
    case 4: // 日干
      currentStep.value = 3
      selectedRiGan.value = null
      selectedRiZhi.value = null
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
    case 5: // 日支
      currentStep.value = 4
      selectedRiZhi.value = null
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
    case 6: // 时干
    case 7: // 时支
      currentStep.value = 5
      selectedShiGan.value = null
      selectedShiZhi.value = null
      break
  }
}



// 日期类型切换
const handleChangeDateType = (type: 'solar' | 'lunar' | 'sizhu') => {
  const oldType = dateType.value
  dateType.value = type
  
  // 如果切换到农历模式，将当前公历时间转换为农历
  if (type === 'lunar' && oldType === 'solar') {
    try {
      const solarTime = SolarTime.fromYmdHms(
        solarYear.value, 
        solarMonth.value, 
        solarDay.value, 
        solarHour.value, 
        solarMinute.value, 
        0
      )
      
      const solarDayObj = solarTime.getSolarDay()
      const lunarDayObj = solarDayObj.getLunarDay()
      const lunarMonthObj = lunarDayObj.getLunarMonth()
      const lunarYearObj = lunarMonthObj.getLunarYear()
      
      // 设置农历年月日
      lunarYear.value = lunarYearObj.getYear()
      
      // 获取农历月份（考虑闰月）
      const lunarMonths = getLunarMonths(lunarYearObj.getYear())
      const currentLunarMonth = lunarMonthObj.getMonth()
      const isLeap = lunarMonthObj.isLeap()
      
      // 找到对应的月份值
      const monthValue = isLeap ? currentLunarMonth + 12 : currentLunarMonth
      const validMonth = lunarMonths.find(m => m.value === monthValue)
      
      if (validMonth) {
        lunarMonth.value = monthValue
      } else {
        // 如果找不到对应的月份，使用第一个可用月份
        lunarMonth.value = lunarMonths[0]?.value || 1
      }
      
      lunarDay.value = lunarDayObj.getDay()
      lunarHour.value = solarHour.value
      lunarMinute.value = solarMinute.value
    } catch (error) {
      console.error('公历转农历失败：', error)
      // 如果转换失败，使用默认的农历时间
      initializeLunarCurrentTime()
    }
  }
  // 如果切换到公历模式，将当前农历时间转换为公历
  else if (type === 'solar' && oldType === 'lunar') {
    try {
      const isLeap = lunarMonth.value > 12
      const lunarMonthValue = isLeap ? -(lunarMonth.value - 12) : lunarMonth.value
      
      // 创建农历日期对象
      const lunarMonthObj = LunarMonth.fromYm(lunarYear.value, lunarMonthValue)
      const lunarDayObj = LunarDay.fromYmd(lunarYear.value, lunarMonthValue, lunarDay.value)
      
      // 获取对应的公历日期
      const solarDayObj = lunarDayObj.getSolarDay()
      const solarMonthObj = solarDayObj.getSolarMonth()
      const solarYearObj = solarMonthObj.getSolarYear()
      
      // 设置公历年月日
      solarYear.value = solarYearObj.getYear()
      solarMonth.value = solarMonthObj.getMonth()
      solarDay.value = solarDayObj.getDay()
      solarHour.value = lunarHour.value
      solarMinute.value = lunarMinute.value
    } catch (error) {
      console.error('农历转公历失败：', error)
      // 如果转换失败，使用默认的公历时间
      const now = new Date()
      solarYear.value = now.getFullYear()
      solarMonth.value = now.getMonth() + 1
      solarDay.value = now.getDate()
      solarHour.value = now.getHours()
      solarMinute.value = now.getMinutes()
    }
  }
  // 如果切换到四柱模式，清空四柱选择
  else if (type === 'sizhu') {
    clearAllSelections()
  }
  
  updateAllWheelPositions()
}


// 计算轮盘偏移量
const calculateOffset = (selectedValue: number, items: number[]) => {
  const index = items.indexOf(selectedValue)
  if (index === -1) return 0

  const visibleOptionNum = 5
  const baseOffset = ITEM_HEIGHT * (visibleOptionNum - 1) / 2
  const offset = baseOffset - (index * ITEM_HEIGHT)

  return offset
}

// 更新所有轮盘位置
const updateAllWheelPositions = () => {
  yearOffset.value = calculateOffset(selectedYear.value, years.value)
  monthOffset.value = calculateOffset(selectedMonth.value, months.value)
  dayOffset.value = calculateOffset(selectedDay.value, days.value)
  hourOffset.value = calculateOffset(selectedHour.value, hours.value)
  minuteOffset.value = calculateOffset(selectedMinute.value, minutes.value)
}

// 触摸事件处理
const handleTouchStart = (e: TouchEvent) => {
  const touch = e.touches[0]
  if (!touch) return

  touchStartY.value = touch.clientY
  touchStartTime.value = Date.now()
  isDragging.value = true
}

const handleTouchMove = (e: TouchEvent) => {
  if (!isDragging.value) return
  e.preventDefault()
}

const handleTouchEnd = (e: TouchEvent) => {
  if (!isDragging.value) return

  isDragging.value = false
  const deltaTime = Date.now() - touchStartTime.value
  const changedTouch = e.changedTouches[0]
  if (!changedTouch) return

  const deltaY = changedTouch.clientY - touchStartY.value

  if (Math.abs(deltaY) > 10) {
    const target = e.target as HTMLElement
    const wheel = target.closest('.picker-wheel')
    if (wheel) {
      const wheelIndex = Array.from(wheel.parentElement?.children || []).indexOf(wheel)
      const items = [years.value, months.value, days.value, hours.value, minutes.value][wheelIndex]
      const currentValue = [selectedYear.value, selectedMonth.value, selectedDay.value, selectedHour.value, selectedMinute.value][wheelIndex]

      if (items && currentValue !== undefined) {
        const currentIndex = items.indexOf(currentValue)

        let stepCount = 1
        if (deltaTime < 200) {
          stepCount = Math.min(Math.abs(deltaY) / 30, 5)
        } else if (deltaTime < 500) {
          stepCount = Math.min(Math.abs(deltaY) / 50, 3)
        }

        const direction = deltaY > 0 ? -1 : 1
        const newIndex = Math.max(0, Math.min(items.length - 1, currentIndex + (direction * Math.round(stepCount))))
        const newValue = items[newIndex]

        if (newValue !== undefined && newValue !== currentValue) {
          switch (wheelIndex) {
            case 0: selectYear(newValue); break
            case 1: selectMonth(newValue); break
            case 2: selectDay(newValue); break
            case 3: selectHour(newValue); break
            case 4: selectMinute(newValue); break
          }
        }
      }
    }
  }
}

// 选择方法
const selectYear = (year: number) => {
  selectedYear.value = year
  if (dateType.value === 'solar') {
    validateDay()
  } else {
    // 农历模式：检查当前选择的月份是否仍然有效
    const lunarMonths = getLunarMonths(year)
    const isValidMonth = lunarMonths.some(m => m.value === selectedMonth.value)
    if (!isValidMonth && lunarMonths.length > 0 && lunarMonths[0]) {
      // 如果当前月份无效（比如之前选择了闰月，但新年份没有闰月），重置为第一个月
      selectedMonth.value = lunarMonths[0].value
      selectedDay.value = 1
    } else {
      validateDay()
    }
  }
  updateAllWheelPositions()
}

const selectMonth = (month: number) => {
  selectedMonth.value = month
  if (dateType.value === 'solar') {
    validateDay()
  }
  updateAllWheelPositions()
}

const selectDay = (day: number) => {
  selectedDay.value = day
  updateAllWheelPositions()
}

const selectHour = (hour: number) => {
  selectedHour.value = hour
  updateAllWheelPositions()
}

const selectMinute = (minute: number) => {
  selectedMinute.value = minute
  updateAllWheelPositions()
}

// 验证方法
const validateDay = () => {
  if (dateType.value === 'solar') {
    const maxDays = new Date(selectedYear.value, selectedMonth.value, 0).getDate()
    if (selectedDay.value > maxDays) {
      selectedDay.value = maxDays
    }
  } else {
    // 农历模式：验证日期是否有效
    const maxDays = getLunarMonthDays(selectedYear.value, selectedMonth.value)
    if (selectedDay.value > maxDays) {
      selectedDay.value = maxDays
    }
  }
}

// 处理今天按钮（公历和农历模式）
const handleToday = () => {
  const today = new Date()
  
  if (dateType.value === 'solar') {
    // 公历模式：直接使用今天的公历日期
    selectedYear.value = today.getFullYear()
    selectedMonth.value = today.getMonth() + 1
    selectedDay.value = today.getDate()
    selectedHour.value = today.getHours()
    selectedMinute.value = today.getMinutes()
  } else if (dateType.value === 'lunar') {
    // 农历模式：将1990年的当前月日时分转换为农历日期
    try {
      const defaultTime = new Date(1990, today.getMonth(), today.getDate(), today.getHours(), today.getMinutes())
      const solarTime = SolarTime.fromYmdHms(
        defaultTime.getFullYear(), 
        defaultTime.getMonth() + 1, 
        defaultTime.getDate(), 
        defaultTime.getHours(), 
        defaultTime.getMinutes(), 
        0
      )
      
      const solarDay = solarTime.getSolarDay()
      const lunarDayObj = solarDay.getLunarDay()
      const lunarMonthObj = lunarDayObj.getLunarMonth()
      const lunarYearObj = lunarMonthObj.getLunarYear()
      
      // 设置农历年月日
      selectedYear.value = lunarYearObj.getYear()
      
      // 获取农历月份（考虑闰月）
      const lunarMonths = getLunarMonths(lunarYearObj.getYear())
      const currentLunarMonth = lunarMonthObj.getMonth()
      const isLeap = lunarMonthObj.isLeap()
      
      // 找到对应的月份值
      const monthValue = isLeap ? currentLunarMonth + 12 : currentLunarMonth
      const validMonth = lunarMonths.find(m => m.value === monthValue)
      
      if (validMonth) {
        selectedMonth.value = monthValue
      } else {
        // 如果找不到对应的月份，使用第一个可用月份
        selectedMonth.value = lunarMonths[0]?.value || 1
      }
      
      selectedDay.value = lunarDayObj.getDay()
      selectedHour.value = defaultTime.getHours()
      selectedMinute.value = defaultTime.getMinutes()
      
      // 验证日期是否有效
      validateDay()
    } catch (error) {
      console.error('农历转换失败：', error)
      // 如果转换失败，回退到公历日期
      selectedYear.value = today.getFullYear()
      selectedMonth.value = today.getMonth() + 1
      selectedDay.value = today.getDate()
      selectedHour.value = today.getHours()
      selectedMinute.value = today.getMinutes()
    }
  }
  
  updateAllWheelPositions()
}

// 处理输入确认
const handleInputConfirm = () => {
  if (datetimeInput.value.length === 0) return
  
  const input = datetimeInput.value.trim()
  
  // 验证输入格式：YYYYMMDDHHMM (12位数字)
  if (!/^\d{12}$/.test(input)) {
    showOptimizedToast('请输入正确的格式：年月日时分（12位数字，如：199805060515）')
    return
  }

  // 解析输入
  const year = parseInt(input.substring(0, 4))
  const month = parseInt(input.substring(4, 6))
  const day = parseInt(input.substring(6, 8))
  const hour = parseInt(input.substring(8, 10))
  const minute = parseInt(input.substring(10, 12))
  
  // 验证日期有效性
  const date = new Date(year, month - 1, day, hour, minute)
  if (date.getFullYear() !== year || 
      date.getMonth() !== month - 1 || 
      date.getDate() !== day ||
      date.getHours() !== hour ||
      date.getMinutes() !== minute) {
    showOptimizedToast('输入的日期时间无效')
    return
  }

  // 设置选中的值
  selectedYear.value = year
  selectedMonth.value = month
  selectedDay.value = day
  selectedHour.value = hour
  selectedMinute.value = minute
  
  // 更新轮盘位置
  updateAllWheelPositions()
  
  // 清空输入框
  datetimeInput.value = ''
}

// 清空输入
const clearInput = () => {
  datetimeInput.value = ''
}

// 处理确认
const handleConfirm = () => {
  // 如果是四柱模式，需要特殊处理
  if (dateType.value === 'sizhu') {
    // 检查是否所有四柱都已选择
    if (isAllSelected()) {
      // 构建四柱字符串
      const sizhuText = `${selectedNianGan.value}${selectedNianZhi.value} ${selectedYueGan.value}${selectedYueZhi.value} ${selectedRiGan.value}${selectedRiZhi.value} ${selectedShiGan.value}${selectedShiZhi.value}`
      emit('confirm', {
        solar: '',
        lunar: '',
        eightChar: sizhuText,
        dateType: 'sizhu'
      })
    } else {
      // 如果四柱未完成，不执行确认
      return
    }
  } else {
    // 公历/农历模式 - 使用本地计算获取四柱信息
    const year = selectedYear.value
    const month = selectedMonth.value
    const day = selectedDay.value
    const hour = selectedHour.value
    const minute = selectedMinute.value

    try {
      let solarTime: SolarTime
      
      if (dateType.value === 'lunar') {
        // 农历模式：需要将农历日期转换为公历日期
        const isLeap = month > 12
        const lunarMonthValue = isLeap ? -(month - 12) : month  // 闰月使用负数
        
        // 创建农历日期对象
        const lunarMonth = LunarMonth.fromYm(year, lunarMonthValue)
        const lunarDay = LunarDay.fromYmd(year, lunarMonthValue, day)
        
        // 获取对应的公历日期
        const solarDay = lunarDay.getSolarDay()
        const solarMonth = solarDay.getSolarMonth()
        const solarYear = solarMonth.getSolarYear()
        
        // 创建公历时间对象
        solarTime = SolarTime.fromYmdHms(
          solarYear.getYear(), 
          solarMonth.getMonth(), 
          solarDay.getDay(), 
          hour, 
          minute, 
          0
        )
      } else {
        // 公历模式：直接创建公历时间对象
        solarTime = SolarTime.fromYmdHms(year, month, day, hour, minute, 0)
      }
        
      // 获取农历时间
      const lunarHour = solarTime.getLunarHour()

      // 获取八字信息
      const eightChar = lunarHour.getEightChar()
      
      // 构建结果对象
      // 获取农历信息
      const solarDayObj = solarTime.getSolarDay()
      const lunarDay = solarDayObj.getLunarDay()
      const lunarMonth = lunarDay.getLunarMonth()
      const lunarYear = lunarMonth.getLunarYear()
      const lunarHourForTime = solarTime.getLunarHour(true)
      const hourName = lunarHourForTime.getSixtyCycle().getEarthBranch().getName() + '时'
      
      const lunarMonthName = lunarMonth.getName()
      const lunarDayName = lunarDay.getName()
      const lunarYearNumber = lunarYear.getYear()
      // 移除农历月份和日期名称中可能包含的年份信息
      const cleanMonthName = lunarMonthName.replace(/\d+年/g, '')
      const cleanDayName = lunarDayName.replace(/\d+年/g, '')
      const lunar = `${lunarYearNumber}年${cleanMonthName}${cleanDayName}日 ${hourName}`

      // 构建结果对象 - 使用转换后的公历日期
      const solarYear = solarTime.getYear()
      const solarMonth = solarTime.getMonth()
      const solarDay = solarTime.getDay()
      
      const result = {
        solar: `${solarYear}-${solarMonth.toString().padStart(2, '0')}-${solarDay.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`,
        lunar: lunar,
        eightChar: eightChar.getName(),
        dateType: dateType.value
      }
      
      emit('confirm', result)
    } catch (error) {
      console.error('日期计算错误：', error)
      // 如果计算失败，回退到简单格式
      const datetimeText = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
      emit('confirm', {
        solar: datetimeText,
        lunar: '',
        eightChar: '',
        dateType: dateType.value
      })
    }
  }
  
  // 清除四柱选择数据
  if (dateType.value === 'sizhu') {
    clearAllSelections()
  }
  
  // 先播放收起动画
  showAnimation.value = false
  // 延迟关闭，等待动画完成
  setTimeout(() => {
    visible.value = false
  }, 300)
}

// 处理取消
const handleCancel = () => {
  // 清除四柱选择数据
  if (dateType.value === 'sizhu') {
    clearAllSelections()
  }
  // 先播放收起动画
  showAnimation.value = false
  // 延迟关闭，等待动画完成
  setTimeout(() => {
    visible.value = false
  }, 300)
}



// 初始化默认值 - 简化版本，直接解析公历日期
const initializeValues = () => {
  if (props.defaultDateTime) {
    // 解析 YYYY-MM-DD HH:mm:ss 格式的公历日期
    const match = props.defaultDateTime.match(/(\d{4})-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2})(?::(\d{1,2}))?/)
    if (match) {
      const [, year, month, day, hour, minute] = match
      if (year && month && day && hour && minute) {
        const yearNum = parseInt(year)
        const monthNum = parseInt(month)
        const dayNum = parseInt(day)
        const hourNum = parseInt(hour)
        const minuteNum = parseInt(minute)
        
        if (dateType.value === 'solar') {
          // 公历模式：直接使用解析的值
          solarYear.value = yearNum
          solarMonth.value = monthNum
          solarDay.value = dayNum
          solarHour.value = hourNum
          solarMinute.value = minuteNum
        } else if (dateType.value === 'lunar') {
          // 农历模式：将公历日期转换为农历显示
          try {
            const solarTime = SolarTime.fromYmdHms(yearNum, monthNum, dayNum, hourNum, minuteNum, 0)
            const solarDay = solarTime.getSolarDay()
            const lunarDayObj = solarDay.getLunarDay()
            const lunarMonthObj = lunarDayObj.getLunarMonth()
            const lunarYearObj = lunarMonthObj.getLunarYear()
            
            lunarYear.value = lunarYearObj.getYear()
            
            const lunarMonths = getLunarMonths(lunarYearObj.getYear())
            const currentLunarMonth = lunarMonthObj.getMonth()
            const isLeap = lunarMonthObj.isLeap()
            const monthValue = isLeap ? currentLunarMonth + 12 : currentLunarMonth
            const validMonth = lunarMonths.find(m => m.value === monthValue)
            
            lunarMonth.value = validMonth ? monthValue : (lunarMonths[0]?.value || 1)
            lunarDay.value = lunarDayObj.getDay()
            lunarHour.value = hourNum
            lunarMinute.value = minuteNum
          } catch (error) {
            console.error('农历转换失败：', error)
            // 回退到公历时间
            lunarYear.value = yearNum
            lunarMonth.value = monthNum
            lunarDay.value = dayNum
            lunarHour.value = hourNum
            lunarMinute.value = minuteNum
          }
        }
        // 四柱模式不需要特殊处理，因为四柱是用户选择的
      }
    }
  } else {
    // 没有默认值，使用当前时间
    const now = new Date()
    solarYear.value = now.getFullYear()
    solarMonth.value = now.getMonth() + 1
    solarDay.value = now.getDate()
    solarHour.value = now.getHours()
    solarMinute.value = now.getMinutes()
    
    // 初始化农历当前时间
    if (dateType.value === 'lunar') {
      initializeLunarCurrentTime()
    }
  }
  updateAllWheelPositions()
}

// 监听弹窗显示
watch(visible, (newVal) => {
  if (newVal) {
    initializeValues()
    // 如果是四柱模式，确保从第一步开始
    if (dateType.value === 'sizhu') {
      currentStep.value = 0
    }
  }
})

// 监听数据变化，更新轮盘位置
watch([selectedYear, selectedMonth, selectedDay, selectedHour, selectedMinute], () => {
  nextTick(() => {
    updateAllWheelPositions()
  })
})


// 键盘事件处理
const handleKeydown = (e: KeyboardEvent) => {
  if (!visible.value) return

  switch (e.key) {
    case 'Escape':
      handleCancel()
      break
    case 'Enter':
      handleConfirm()
      break
  }
}

onMounted(() => {
  if (visible.value) {
    document.addEventListener('keydown', handleKeydown)
  }
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown)
  // 清理 Toast 定时器
  if (toastTimer.value) {
    clearTimeout(toastTimer.value)
  }
})

watch(visible, (newVal) => {
  if (newVal) {
    document.body.style.overflow = 'hidden'
    document.addEventListener('keydown', handleKeydown)
    // 延迟触发动画，确保DOM已渲染
    setTimeout(() => {
      showAnimation.value = true
    }, 50)
  } else {
    showAnimation.value = false
    document.body.style.overflow = ''
    document.removeEventListener('keydown', handleKeydown)
  }
})
</script>

<style scoped>
.custom-datetime-picker {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.picker-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 1;
  transition: opacity 0.3s ease-out;
  z-index: 1;
}

/* 遮罩层显示状态 */
.custom-datetime-picker .picker-overlay {
  opacity: 1;
}

/* 收起时的遮罩层淡出效果 */
.custom-datetime-picker.picker-closing .picker-overlay {
  opacity: 0;
}

.picker-container {
  position: relative;
  width: 100%;
  background: #ffffff;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform: translateY(100%);
  transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94), height 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.2);
  z-index: 2;
}

.picker-container--show {
  transform: translateY(0);
}

/* 不同tab模式的高度动画 */
.picker-container--solar {
  height: 450px;
}

.picker-container--lunar {
  height: 450px;
}

.picker-container--sizhu {
  height: 600px;
}

.picker-header {
  display: flex;
  flex-direction: column;
  padding: 24px 12px 12px 12px;
  border-bottom: 1px solid #f1f5f9;
  flex-shrink: 0;
  background: #ffffff;
  position: relative;
  z-index: 4;
}

.picker-header-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.picker-btn {
  background: none;
  border: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  height: 40px;
  padding: 0 20px;
  border-radius: 20px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
}

.picker-cancel {
  color: #64748b;
}

.picker-cancel:hover {
  background: #f1f5f9;
}

.picker-confirm {
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  color: #d4af37;
  border: none;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.picker-confirm:hover {
  background: linear-gradient(135deg, #0f0f0f 0%, #1a1a1a 100%);
  color: #f4d03f;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
}

/* 今天按钮样式 */
.picker-today-btn {
  width: 40px;
  height: 40px;
  background: #f8fafc;
  border: none;
  border-radius: 50%;
  font-size: 16px;
  font-weight: 500;
  color: #475569;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  white-space: nowrap;
}

/* 移除今天按钮的hover效果 */

.picker-tabs {
  display: flex;
  background: #fafbfc;
  border-radius: 24px;
  padding: 1px;
  border: 1px solid #f1f5f9;
  height: 44px;
  min-width: 240px;
}

.picker-tab {
  flex: 1;
  height: 36px;
  padding: 0 24px;
  background: none;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #94a3b8;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picker-tab--active {
  background: #ffffff;
  color: #1e293b;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
}

/* 左侧按钮组 */
.picker-header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

/* 快速输入区域样式已移除，使用quick-input-container */

.quick-input-container {
  width: 100%;
}

.input-group {
  display: flex;
  gap: 8px;
  align-items: center;
  background: #f1f5f9;
  border: 1px solid #f1f5f9;
  border-radius: 24px;
  padding: 4px;
}

.input-wrapper {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

.datetime-input {
  flex: 1;
  height: 36px;
  padding: 0 16px;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  color: #1e293b;
  background: transparent;
  transition: all 0.2s ease;
}

.datetime-input:focus {
  outline: none;
  background: transparent;
}

.datetime-input::placeholder {
  color: #94a3b8;
  font-size: 12px;
}

.clear-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  border: none;
  background: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #94a3b8;
  transition: color 0.2s ease;
  z-index: 1;
}

.clear-btn:hover {
  color: #64748b;
}

.clear-btn:active {
  color: #475569;
}

.input-confirm-btn {
  height: 36px;
  padding: 0 24px;
  background: #ffffff;
  color: #1e293b;
  border: 1px solid #e2e8f0;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: not-allowed;
  transition: all 0.2s ease;
  white-space: nowrap;
  opacity: 0.4;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  min-width: 80px;
}

.input-confirm-btn:not(:disabled) {
  cursor: pointer;
  opacity: 1;
}

.input-confirm-btn--active {
  background: #ffffff;
  color: #1e293b;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  opacity: 1;
}

.input-confirm-btn--active:hover {
  background: #f8fafc;
  color: #0f172a;
}

.quick-input-group {
  display: flex;
  gap: 8px;
}

.quick-input-item {
  flex: 1;
  height: 40px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s ease;
}

.quick-input-item--active {
  border-color: #3b82f6;
  background: #eff6ff;
  color: #3b82f6;
}


/* 主要内容区域 */
.picker-content {
  flex: 1;
  padding: 20px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 300px;
  transition: height 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.picker-title {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.picker-title span {
  flex: 1;
  text-align: center;
}

.picker-wheels {
  display: flex;
  flex: 1;
  overflow: hidden;
  position: relative;
  height: 200px;
}

.picker-wheel {
  flex: 1;
  height: 200px;
  position: relative;
  overflow: hidden;
  background: transparent;
}

.wheel-content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  transition: transform 0.3s ease-out;
}

.wheel-item {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #1e293b;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  font-size: 14px;
}

.wheel-item:hover {
  color: #1e293b;
}

.wheel-item--active {
  color: #1e293b;
  font-weight: bold;
  font-size: 18px;
}

/* 选择框 - 透明样式 */
.picker-frame {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 40px;
  transform: translateY(-50%);
  background: rgba(59, 130, 246, 0.05);
  pointer-events: none;
  z-index: 2;
}



/* 整体遮罩层 - 只覆盖轮盘区域 */
.picker-global-mask {
  position: absolute;
  top: 60px;
  /* 从header下方开始 */
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom,
      rgba(255, 255, 255, 0.8) 0%,
      rgba(255, 255, 255, 0.3) 20%,
      rgba(255, 255, 255, 0) 50%,
      rgba(255, 255, 255, 0) 50%,
      rgba(255, 255, 255, 0.3) 80%,
      rgba(255, 255, 255, 0.8) 100%);
  pointer-events: none;
  z-index: 3;
}

/* 四柱内容区域 - 参考Dart实现 */
.picker-sizhu-content {
  padding: 20px;
  background: #ffffff;
  position: relative;
  z-index: 4;
  width: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  transition: height 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  overflow-y: auto;
  min-height: 0;
}

/* 四柱显示区域 */

.sizhu-titles {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
}

.sizhu-title {
  font-size: 14px;
  color: #666666;
  text-align: center;
}

.sizhu-row {
  display: flex;
  justify-content: space-around;
  margin-bottom: 15px;
}

.sizhu-circle {
  width: 66px;
  height: 66px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s ease;
}

.sizhu-circle.sizhu-circle--active {
  background: #e5e7eb;
  color: #374151;
}

.sizhu-circle:hover {
  transform: scale(1.05);
}

.sizhu-circle--disabled {
  opacity: 0.5;
  cursor: not-allowed !important;
  pointer-events: none;
}

.sizhu-circle--disabled:hover {
  transform: none !important;
}

/* 选择区域 */
.sizhu-selection {
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}


.selection-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  margin-bottom: 20px;
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.selection-item {
  width: 100%;
  height: 65px;
  background: #f4f4f4;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s ease;
}

.selection-item:hover {
  background: #f1f5f9;
  transform: scale(1.05);
}

.combination-item {
  width: 100%;
  height: 45px;
  background: #f8f9fa;
  border: 1px solid #dddddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 2px;
}

.combination-item:hover {
  background: #f1f5f9;
  transform: scale(1.05);
}

/* 柱位选择网格 - 五列两排布局 */
.selection-grid--pillar {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  max-width: 100%;
}

/* 柱位组合项 - 水平布局 */
.combination-item--pillar {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px 12px;
  min-height: 60px;
  white-space: nowrap;
}

.combination-text {
  display: flex;
  align-items: center;
  gap: 2px;
  white-space: nowrap;
}

.combination-tiangan {
  font-size: 18px;
  font-weight: bold;
  line-height: 1;
  white-space: nowrap;
}

.combination-dizhi {
  font-size: 18px;
  font-weight: bold;
  line-height: 1;
  white-space: nowrap;
}

/* 分组选择网格 */
.selection-grid--grouped {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 5px;
  max-width: 100%;
}

/* 组合分组 */
.combination-group {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 0;
}

.group-tiangan {
  font-size: 20px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 4px;
}

.group-dizhi-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center;
  align-items: center;
  min-height: 48px;
}

.dizhi-button {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  border: none;
  border-radius: 8px;
  background: #f4f4f4;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 2px;
}

/* 大按钮 - 单个地支 */
.dizhi-button--large {
  width: 66px;
  height: 66px;
  font-size: 22px;
  font-weight: bold;
}

/* 小按钮 - 多个地支 */
.dizhi-button--small {
  width: 65px;
  height: 29px;
  font-size: 18px;
  font-weight: bold;
}

.button-tiangan {
  font-weight: bold;
}

.button-dizhi {
  font-weight: bold;
}

.dizhi-button:hover {
  background: #e5e5e5;
  transform: scale(1.05);
}

/* 日期选择样式 */


.date-selection-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow-y: auto;
  max-height: 200px;
  padding: 18px 0;
  transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  /* 隐藏滚动条但保留滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE和Edge */
}

.date-selection-grid::-webkit-scrollbar {
  display: none; /* Chrome、Safari和Opera */
}

.date-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 16px 20px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  width: 100%;
  text-align: left;
}

.date-item:hover {
  background: #f8fafc;
  border-color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}


.date-text {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  text-align: left;
}

.date-gregorian {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
}

.date-lunar {
  font-size: 16px;
  font-weight: 600;
  color: #64748b;
}

/* 底部按钮区域 */
.sizhu-buttons {
  display: flex;
  gap: 10px;
  flex-shrink: 0;
  background: #ffffff;
  margin-top: 20px;
}

.btn-previous {
  flex: 1;
  height: 50px;
  background: #f5f5f5;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #666666;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-previous:hover {
  background: #e2e8f0;
}

.btn-clear {
  height: 50px;
  padding: 0 20px;
  background: #f5f5f5;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #666666;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-clear:hover {
  background: #e2e8f0;
}

/* 搜索结果样式 */
.search-loading {
  padding: 30px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: #3b82f6;
}

.search-results {
  padding: 20px;
}

.results-title {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
  text-align: center;
}

.results-list {
  max-height: 300px;
  overflow-y: auto;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #ffffff;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.result-item:hover {
  background: #f8fafc;
  border-color: #3b82f6;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-number {
  width: 24px;
  height: 24px;
  background: #3b82f6;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  margin-right: 12px;
}

.result-date {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #1e293b;
}

.result-arrow {
  color: #3b82f6;
  font-size: 16px;
}

.no-results {
  padding: 40px 20px;
  text-align: center;
}

.no-results-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-results-text {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 8px;
}

.no-results-hint {
  font-size: 14px;
  color: #64748b;
}

/* 查找范围提示 */
.sizhu-range-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 16px 0;
  width: 100%;
}

.range-text {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.current-selection {
  font-size: 12px;
  color: #3b82f6;
  margin-top: 4px;
  font-weight: 600;
}

.range-clear {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 12px;
  background: #f4f4f4;
  border-radius: 20px;
  font-size: 14px;
  gap: 3px;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s ease;
  line-height: 1;
}

.range-clear:hover {
  background: #e5e5e5;
  color: #475569;
}






/* 自定义 Toast 样式 */
.custom-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10000;
  opacity: 0;
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  pointer-events: none;
  width: 100%;
  max-width: 90vw;
  padding: 0 20px;
  box-sizing: border-box;
  animation: toastSlideIn 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
}

.custom-toast.toast-show {
  opacity: 1;
  pointer-events: auto;
}

@keyframes toastSlideIn {
  0% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.8);
  }
  100% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}

.toast-content {
  background: rgba(0, 0, 0, 0.9);
  color: white;
  padding: 10px 14px;
  border-radius: 12px;
  min-width: 160px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  max-width: 400px;
  word-wrap: break-word;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  position: relative;
  overflow: hidden;
}

.toast-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #3b82f6, #8b5cf6, #06b6d4);
  opacity: 0.8;
}

.toast-icon {
  flex-shrink: 0;
  margin-top: 2px;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toast-message {
  font-size: 11px;
  line-height: 1.3;
  flex: 1;
  text-align: left;
  word-break: break-word;
  white-space: pre-wrap;
  font-weight: 500;
  letter-spacing: 0.01em;
}

/* Toast 类型样式 */
.toast-error .toast-content {
  background: rgba(239, 68, 68, 0.95);
  border-color: rgba(239, 68, 68, 0.3);
}

.toast-error .toast-content::before {
  background: linear-gradient(90deg, #ef4444, #dc2626);
}

.toast-success .toast-content {
  background: rgba(34, 197, 94, 0.95);
  border-color: rgba(34, 197, 94, 0.3);
}

.toast-success .toast-content::before {
  background: linear-gradient(90deg, #22c55e, #16a34a);
}

.toast-warning .toast-content {
  background: rgba(245, 158, 11, 0.95);
  border-color: rgba(245, 158, 11, 0.3);
}

.toast-warning .toast-content::before {
  background: linear-gradient(90deg, #f59e0b, #d97706);
}

.toast-info .toast-content {
  background: rgba(59, 130, 246, 0.95);
  border-color: rgba(59, 130, 246, 0.3);
}

.toast-info .toast-content::before {
  background: linear-gradient(90deg, #3b82f6, #2563eb);
}

/* 长文本优化 */
.toast-message {
  max-height: 60px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

.toast-message::-webkit-scrollbar {
  width: 4px;
}

.toast-message::-webkit-scrollbar-track {
  background: transparent;
}

.toast-message::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

.toast-message::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}


</style>